package com.plian.system.service.sys.orgzation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.OrgCache;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.RedisUtils;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.property.PropertyDao;
import com.plian.system.dao.pm.property.PropertyRecordDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.pm.property.PropertyBasics;
import com.plian.system.entity.sys.OrgRelation;
import com.plian.system.enumeratea.FormTableEnum;
import com.plian.system.mapper.pm.property.PropertyBasicsMapper;
import com.plian.system.mapper.sys.OrgRelationMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.fr.indicatorsvalue.IGraphicOrgRelationService;
import com.plian.system.service.pm.property.IPropertyBasicsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrgzationService {
    @Autowired
    OrgzationDao orgzationDao;

    @Autowired
    OrgRelationMapper orgRelationMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(OrgzationService.class);

    @Autowired
    PropertyBasicsDao propertyBasicsDao;

    @Autowired
    PropertyDao propertyDao;

    @Autowired
    PropertyRecordDao propertyRecordDao;

    @Autowired
    IGraphicOrgRelationService graphicOrgRelationService;

    @Autowired
    private IPropertyBasicsService propertyBasicsService;

    @Autowired
    private GzwProperties gzwProperties;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IOrgService orgService;

    @Resource
    PropertyBasicsMapper propertyBasicsMapper;

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd) {
        ObjResult objResult;

        try {
            String name = pd.getString("name");
            if(StringUtils.isBlank(name)) return new ObjResult("请填写单位名称");
            PageData repeat = orgzationDao.findRepeatName(name.trim());
            if(null != repeat) return new ObjResult("单位名称重复");
            if (Tools.isEmpty(pd.getString("parentId"))) {
                pd.put("parentId", "0");
            }
            pd.put("id", UuidUtil.get32UUID());
            pd.put("createTime", DateUtil.now());
            orgzationDao.save(pd);
            OrgCache.update(pd.getString("id"));
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            objResult = new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return objResult;
    }

    /**
     * 修改
     *
     * @param pd
     * @return
     */
    public ObjResult edit(PageData pd) {
        ObjResult objResult;
        if (pd.getString("id").equals(pd.getString("parentId"))) {
            objResult = new ObjResult(CommonCode.FAIL);
            objResult.setMessage("父id重复!");
        } else {
            try {
                String id = pd.getString("id");
                PageData oldpd = orgzationDao.findbyid(id);
                //修改父类的预算表类型
                //新的父类id
                String parentId = pd.getString("parentId");
                //旧的父类id
                String oldparentId = pd.getString("oldparentId");
                //判断新旧是否相同
                if (parentId.equals(oldparentId)){
                    String orgCode = pd.getString("orgCode");
                    if(StringUtils.isNotBlank(orgCode) && !orgCode.equals(oldpd.getString("orgCode"))){
                        oldpd.put("orgCode",orgCode);
                    }
                }else {
                    //id找到
                    PageData findbyid = orgzationDao.findbyid(parentId);
                    if (oldparentId != null){
                        PageData oldfindbyid = orgzationDao.findbyid(oldparentId);
                        Integer oldtypeCode = oldfindbyid.getInteger("typeCode");
                        if (oldtypeCode == 0){
                            PageData pd2 = new PageData();
                            pd2.put("parentId", oldparentId);
                            List<PageData> list = orgzationDao.list(pd2);
                            if (list.size() == 1){
                                oldfindbyid.put("typeCode","1");
                                //保存以前的父节点
                                orgzationDao.edit(oldfindbyid);
                                OrgCache.update(oldfindbyid.getString("id"));
                            }
                        }
                        //判断orgCode
                        PageData pd2 = new PageData();
                        String Orgcode = findbyid.getString("orgCode");
                        pd2.put("parentId", parentId);
                        List<PageData> list = orgzationDao.list(pd2);
                        Integer orgnum = 0;
                        for (PageData pageData : list){
                            //截取最后两位
                            String orgCode = pageData.getString("orgCode");
                            Integer tempnum = Integer.valueOf(orgCode.substring(orgCode.length()-2,orgCode.length()));
                            if (tempnum>orgnum){
                                orgnum = tempnum;
                            }
                        }
                        //int size = list.size()+1;
                        orgnum = orgnum+1;
                        if (orgnum < 10){
                            Orgcode = Orgcode+"0"+orgnum;
                        }else {
                            Orgcode = Orgcode+orgnum;
                        }
                        oldpd.put("orgCodeYN","Y");
                        oldpd.put("orgCode", Orgcode);
                        oldpd.put("parentId",parentId);
                    }
                    //判断预算表类型
                    Integer typeCode = findbyid.getInteger("typeCode");
                    if (typeCode != null){
                        if (typeCode == 1){
                            findbyid.put("typeCode","0");
                            //保存父节点
                            orgzationDao.edit(findbyid);
                            OrgCache.update(findbyid.getString("id"));
                        }
                    }
                    if (pd.getString("orgCode") != null){
                        String orgCodeYN = oldpd.getString("orgCodeYN");
                        if (orgCodeYN == null){
                            oldpd.put("orgCode", pd.getString("orgCode"));
                        }
                    }
                    oldpd.put("updateTime", DateUtil.now());
                }
                //pd.put("typeCode",typeCode1);
                String name = pd.getString("name");
                redisUtils.delOne("getCompanyNameById::"+id);
                if (name != null){
                    oldpd.put("name",name);
                }
                String orgderNum = pd.getString("orgderNum");
                if (orgderNum != null){
                    oldpd.put("orgderNum",orgderNum);
                }
                String forgzw = pd.getString("forgzw");
                if(forgzw!=null&&!forgzw.equals("")){
                    oldpd.put("forgzw",forgzw);
                }

                String isunit = pd.getString("isunit");
                if(StringUtils.isNotBlank(isunit)){
                    oldpd.put("isunit",isunit);
                }

                orgzationDao.edit(oldpd);
                OrgCache.update(oldpd.getString("id"));

                //父亲节点orgCode修改，下面的子集全部修改
                editByPid(oldpd);

//                //更改FORGZW
//                List<PageData> list = orgzationDao.list(null);
//                for (PageData pageData:list){
//                    editForGzw(pageData);
//                }

                //产权树与组织树的自动绑定
                List<PageData> list_pro = propertyBasicsDao.list(null);
                for (PageData pro : list_pro) {
                    if (pd.getString("name").equals(pro.getString("orgName"))) {
                        PageData pd3 = new PageData();
                        pd3.put("id", pro.getString("id"));
                        pd3.put("orgId", pd.getString("id"));
                        propertyBasicsDao.editByOrgId(pd3);
                        propertyDao.editByOrgId(pd3);
                        break;
                    }
                }
                objResult = new ObjResult(CommonCode.SUCCESS);
            } catch (Exception e) {
                objResult = new ObjResult(CommonCode.FAIL);
                log.error(ExceptionUtils.getFullStackTrace(e));
            }
        }
        return objResult;
    }

    /**
     * 父亲节点orgCode修改，下面的子集全部修改
     * @param oldpd
     */
    public void editByPid(PageData oldpd){
        List<PageData> list = null;
        //父亲节点orgCode修改，下面的子集全部修改
        String id1 = oldpd.getString("id");
        String orgCode = oldpd.getString("orgCode");
        PageData pageData = new PageData();
        pageData.put("parentId", id1);
        try {
            list = orgzationDao.list(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        int q = 1;
        for (PageData pd2:list){
            String orgcode = new String();
                if (q < 10){
                    orgcode = orgCode+"0"+q;
                }else {
                    orgcode = orgCode+q;
                }
                pd2.put("orgCode",orgcode);
                try {
                    orgzationDao.edit(pd2);
                } catch (Exception e) {
                    log.error(ExceptionUtils.getFullStackTrace(e));
                }
                if (orgcode.length() > 4){
                    String substring = orgcode.substring(0, 4);
                    if (!("0001".equals(substring))){
                        pd2.put("forGzw",0);
                        try {
                            orgzationDao.editForGzw(pd2);
                        } catch (Exception e) {
                            log.error(ExceptionUtils.getFullStackTrace(e));
                        }
                    }
                }
            OrgCache.update(pd2.getString("id"));
                q++;
            }
    }

    /**
     * 更改FORGZW
     */
    public void editForGzw(PageData pd){
        String orgCode = pd.getString("orgCode");
        if (orgCode.length() > 4){
            String substring = orgCode.substring(0, 4);
            if (!("0001".equals(substring))){
                pd.put("forGzw",0);
                try {
                    orgzationDao.editForGzw(pd);
                } catch (Exception e) {
                    log.error(ExceptionUtils.getFullStackTrace(e));
                }
            }
        }
    }

    /**
     * 删除
     *
     * @return
     */
    public ObjResult del_ids(List<String> list) {
        ObjResult objResult;
        try {
            /*修改为删除状态*/
            orgzationDao.edit_del_ids(list);
            OrgCache.evictBatch(list);
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            objResult = new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return objResult;
    }

    /**
     * 根据id查询
     *
     * @param p
     * @throws Exception
     */
    public ObjResult findbyid(PageData p) {
        ObjResult objResult;
        try {
            PageData p_user = orgzationDao.findbyid(p.getString("id"));
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p_user);
        } catch (Exception e) {
            objResult = new ObjResult(CommonCode.ERROR);
            log.error(ExceptionUtils.getFullStackTrace(e));
            return objResult;
        }
        return objResult;
    }

    /**
     * 批量调整
     *
     * @param p
     * @throws Exception
     */
    public ObjResult adjustment(PageData p) {
        ObjResult objResult;
        try {
            List<String> list = (List<String>) p.get("ids");
            String parentId = p.getString("parentId");
            if (Tools.isEmpty(parentId)) {
                parentId = "0";
            }
            boolean isrepeat = true;
            for (String s : list) {
                if (s.equals(parentId)) {
                    isrepeat = false;
                    break;
                }
            }
            if (isrepeat) {
                orgzationDao.adjustment(p);
                OrgCache.evictBatch(list);
                objResult = new ObjResult(CommonCode.SUCCESS);
            } else {
                objResult = new ObjResult(CommonCode.ERROR);
                objResult.setMessage("父级重复!!!");
            }
        } catch (Exception e) {
            objResult = new ObjResult(CommonCode.ERROR);
            log.error(ExceptionUtils.getFullStackTrace(e));
            return objResult;
        }
        return objResult;
    }

    /**
     * 获取单位树
     */
    public ListResult orgZtree(PageData pd) {
        ListResult listResult;
        try {
            List<PageData> orgAll = orgzationDao.list(pd);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.NoParentIdtree(orgAll);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list_tree);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取单位树 包含本级
     */
    public ListResult orgTree(String parentId) {
        ListResult listResult;
        try {
            PageData p = orgzationDao.findbyid(parentId);
            List<PageData> orgAll = orgzationDao.list(null);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getChlid(parentId, orgAll);
            p.put("children", list_tree);
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }


    /**
     * 获取下级及本级单位树
     */
    public ListResult getSubordinate() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.list(null);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getChlid(orgId, orgAll);
            p.put("children", list_tree);
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取下级及本级单位树
     */
    public ListResult getUnitSubordinate() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.list(null);
            orgAll =  orgAll.stream().filter(o -> (!"2".equals(o.getString("type")))
                    || "1".equals(o.getString("isunit"))).collect(Collectors.toList());
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getChlid(orgId, orgAll);
            p.put("children", list_tree);
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取下级及本级单位树
     */
    public ListResult getSubordinateNoEmptyChildren() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.list(null);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getNoEmptyChild(orgId, orgAll);
            if (CollectionUtil.isNotEmpty(list_tree)){
                p.put("children", list_tree);
            }
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }
    /**
     * 获取下级及本级单位树
     */
    public ListResult getSubordinateByBasics() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            PageData pd1=new PageData();
            pd1.put("competentOrganization", TokenUtil.getCompetentOrganization());
            List<PageData> orgAll = orgzationDao.listByBasics(pd1);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getNoEmptyChild(orgId, orgAll);
            if (CollectionUtil.isNotEmpty(list_tree)){
                p.put("children", list_tree);
            }
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取登录账号下所有下级单位list 包含本级
     * @return
     */
    public List<PageData> getSubordinateList(){
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.list(null);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> listTree = treeUtli.getChlid(orgId, orgAll);
            List<PageData> list = new ArrayList<>();
            list.add(p);
            list.addAll(getAllChildren(listTree));
            return list;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }


    /**
     * 获取一级国资委单位及所有下级单位list
     * @return
     */
    public List<PageData> getGzwSubordinateList(){
        try {
            String nowStr = DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
            List<PageData> gzwUnits = new ArrayList<>();
            if (orgService.getDTFlag(nowStr)){
                gzwUnits  = orgzationDao.findGZWUnitsFilterDT();
            }else {
                gzwUnits = orgzationDao.findGZWUnits();
            }

            Map<String,PageData> orgMap=new HashMap<>();
            List<PageData> orgAll=orgzationDao.list(null);
            orgMap=orgAll.stream().collect(Collectors.toMap(record->record.getString("id"),record->record));
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list = new ArrayList<>();
            List<PageData> reslutList=new ArrayList<>();
            for(PageData pageData:gzwUnits){
                String orgId=pageData.getString("id");
                for(PageData pd:orgAll){
                    if(pd.getString("id").equals(orgId)){
                        reslutList.add(pd);
                    }
                }
                treeUtli.getChlidNoTree(orgId, orgAll,reslutList,orgMap);
            }

            return reslutList;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    private List<PageData> getAllChildren(List<PageData> listTree){
        List<PageData> allList = new ArrayList<>();
        for (PageData tree : listTree){
            allList.add(tree);
            List<PageData> childrenList = (List<PageData>)tree.get("children");
            if (CollectionUtil.isNotEmpty(childrenList)){
                allList.addAll(getAllChildren(childrenList));
            }
        }
        return allList;
    }

    /**
     * 返回父节点下面的所有非树状子节点单位
     * @param id
     * @param orgAll
     * @param resultList
     */
    public void getAllChildrenNoTreeByPid(String id, List<PageData> orgAll,List<PageData> resultList){
        for(PageData p:orgAll){
            String pid=p.getString("parentId");
            String orgId=p.getString("orgId");
            if(pid.equals(id)){
                resultList.add(p);
                getAllChildrenNoTreeByPid(orgId,orgAll,resultList);
            }
        }
    }

    /**
     * 获取下级及本级单位树 (根据 sys_org_relation表特殊处理)
     */
    public ListResult getRelationSubordinate() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.list(null);

            List<OrgRelation> orgRelations = orgRelationMapper.selectList(new QueryWrapper<OrgRelation>().eq("type", 1));

            if (CollectionUtil.isNotEmpty(orgRelations)){
               Map<String, String> map = orgRelations.stream().collect(Collectors.toMap(OrgRelation::getOrgId, OrgRelation::getParentId));
               for (PageData pd : orgAll){
                   if (map.containsKey(pd.getString("id"))){
                       pd.put("parentId", map.get(pd.getString("id")));
                   }
               }
            }

            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getChlid(orgId, orgAll);
            p.put("children", list_tree);
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取登录用户所属单位 所有的下级单位id
     * @return
     */
    public List<String> getSubordinateIds(){
        ListResult listResult = getSubordinate();
        List<String> ids = new ArrayList<>();
        PageData org = (PageData)listResult.getList().get(0);
        ids.add((String)org.get("id"));
        if (org.containsKey("children")){
            getAllChildIds(ids, (List<PageData>)org.get("children"));
        }
        return ids;
    }

    /**
     * 获取所有下级id
     * @param orgId
     * @return
     */
    public List<String> getAllChildIds(String orgId){
        ListResult listResult = orgTree(orgId);
        List<String> ids = new ArrayList<>();
        PageData org = (PageData)listResult.getList().get(0);
        ids.add((String)org.get("id"));
        if (org.containsKey("children")){
            getAllChildIds(ids, (List<PageData>)org.get("children"));
        }
        return ids;
    }

    private void getAllChildIds(List<String> ids, List<PageData> children){
        if (CollectionUtil.isNotEmpty(children)){
            for (PageData child : children){
                ids.add((String)child.get("id"));
                if (child.containsKey("children")){
                    getAllChildIds(ids, (List<PageData>)child.get("children"));
                }
            }
        }
    }



    public ListResult getChlid(PageData pd) {
        ListResult listResult;
        try {
            String orgId = pd.getString("orgId");
            List<PageData> orgList = new ArrayList<>();
            List<String> mergeOrgIds = graphicOrgRelationService.getMergeChildList(orgId);
            if (CollectionUtil.isNotEmpty(mergeOrgIds)){
                int startIndex = 0;
                for (String mergeOrgId : mergeOrgIds){
                    orgList.addAll(getChlidList(mergeOrgId));
                    PageData org = orgzationDao.findbyid(mergeOrgId);
                    if ("1".equals(org.getString("isunit"))){
                        orgListAdd(org, orgList, startIndex);
                    }
                    startIndex = orgList.size();
                }

                String rootName = graphicOrgRelationService.getParentNameByParentId(orgId);
                PageData root = new PageData();
                root.put("orgId", orgId + "united");
                root.put("id", orgId + "united");
                root.put("orgName", rootName + ("(集团汇总)"));
                root.put("name", rootName + ("(集团汇总)"));
                orgList.add(0, root);
            }else {
                orgList = getChlidList(orgId);
                PageData org = orgzationDao.findbyid(pd.getString("orgId"));
                if ("1".equals(org.getString("isunit"))){
                    orgListAdd(org, orgList, 0);
                }
            }

            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(orgList);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    private void orgListAdd(PageData org, List<PageData> orgList, int index){
        org.put("orgId", org.getString("id") + "united");
        org.put("id", org.getString("id") + "united");
        org.put("orgName", org.getString("name") + ("(集团汇总)"));
        org.put("name", org.getString("name") + ("(集团汇总)"));
        orgList.add(index, org);
    }


    /**
     * 获取不包含本级单位的 单位数组
     * @param pd
     * @return
     */
    public ListResult getChildren(PageData pd) {
        ListResult listResult;
        try {
            String orgId = pd.getString("orgId");
            List<PageData> orgList = getChlidList(orgId);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(orgList);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取顶级菜单及下级菜单，并筛选虚拟节点
     *
     * @return
     */
    public ListResult<PageData> getOneUnit(boolean isToken) {
        PageData pd = new PageData();
        pd.put("parentId", "0");

        //获取顶级
        List<PageData> l = new ArrayList<>();
        try {
            PageData org = orgzationDao.findbyid(TokenUtil.getTokenOrgId());
            boolean isGzw = true;
            if (isToken && !"0".equals(org.getString("parentId"))) {
                isGzw = false;
            }
            List<PageData> list = new ArrayList<>();
            if (isGzw){
                l = orgzationDao.list(pd);
                List<PageData> all = orgzationDao.listForGzw();
                for (PageData parent : l) {
                    String id = parent.getString("id");
                    list.add(parent);
                    list.addAll(getOne(id, all, null));
                }
            }else {
                list.add(org);
            }

            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }


    }


    public ListResult<PageData> getOneUnit2(String orgId) {
        PageData pd = new PageData();
        pd.put("parentId", "0");

        //获取顶级
        List<PageData> l = new ArrayList<>();
        try {
            PageData org = orgzationDao.findbyid(orgId);
            boolean isGzw = true;
            if (!"0".equals(org.getString("parentId"))) {
                isGzw = false;
            }
            List<PageData> list = new ArrayList<>();
            if (isGzw){
                l = orgzationDao.list(pd);
                List<PageData> all = orgzationDao.listForGzw();
                for (PageData parent : l) {
                    String id = parent.getString("id");
                    list.add(parent);
                    list.addAll(getOne(id, all, null));
                }
            }else {
                list.add(org);
            }

            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }


    }


    private List<PageData> getOne(String id, List<PageData> all, List<PageData> l) {
        if (l == null) {
            l = new ArrayList<>();
        }
        for (PageData a : all) {
            if (a.getString("parentId").equals(id)) {
                if ("3".equals(a.getString("type"))) {
                    //拿到子集
                    getOne(a.getString("id"), all, l);
                } else {
                    l.add(a);
                    continue;
                }
            }
        }
        return l;
    }

    /**
     * 获取父级下的子集
     */
    public List<PageData> getChlidList(String pid) throws Exception {
        List<PageData> orgAll = orgzationDao.list(null);
        List<PageData> l = new ArrayList<>();
        for (PageData pageData : orgAll) {
            if (pid.equals(pageData.getString("id"))) {
                l.add(pageData);
            }
        }
        TreeUtli treeUtli = new TreeUtli();
        List<PageData> list_tree = treeUtli.getChlidList(pid, orgAll, l);
        return list_tree;
    }

    /**
     * 获取父级集合（全面预算获取父级长度，给新建的单据增加合并标识码）
     */
    public List<PageData> getParentList(String pid, List<PageData> l) throws Exception {
        List<PageData> orgAll = orgzationDao.list(null);
//        List<PageData> l=new ArrayList<>();
        for (PageData pageData : orgAll) {
            if (pid.equals(pageData.getString("id"))) {
                l.add(pageData);
                if (!pageData.getString("parentId").equals(0)) {
                    getParentList(pageData.getString("parentId"), l);
                }
            }
        }
        return l;
    }

    @Cacheable(value = "getCompanyNameById", key = "#id")
    public PageData getCompanyNameById(String id) {
        try {
            PageData p = orgzationDao.findbyid(id);
            return p;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    public String getNameById(String id){
        if (StringUtil.isBlank(id)){
            return null;
        }
        PageData org = getCompanyNameById(id);
        if(org != null){
           return org.getString("name");
        }
        return null;
    }

    public ObjResult listAll() {
        try {
            List<PageData> list = orgzationDao.list(null);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            PageData pd = new PageData();
            pd.put("list", list);
            objResult.setPageData(pd);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult());
        }
    }
    public ObjResult listAllByBasics() {
        try {
            PageData pd1=new PageData();
            pd1.put("competentOrganization", TokenUtil.getCompetentOrganization());
            List<PageData> list = orgzationDao.listByBasics(pd1);
            ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
            PageData pd = new PageData();
            pd.put("list", list);
            objResult.setPageData(pd);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException(new ObjResult());
        }
    }

    /**
     * 获取集团
     *
     * @return
     */
    public ListResult<PageData> getGroup() {
        try {
            String nowStr = DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
            List<PageData> gzwUnits = new ArrayList<>();
            if (orgService.getDTFlag(nowStr)){
                gzwUnits  = orgzationDao.findGZWUnitsFilterDT();
            }else {
                gzwUnits = orgzationDao.findGZWUnits();
            }
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(gzwUnits);
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 获取国资及集团
     *
     * @return
     */
    public ListResult getGroupAndState() {
        //集团
        try {
            List<PageData> l1 = orgzationDao.findbyPid("0");
            PageData org = new PageData();
            List<PageData> l = new ArrayList<>();
            for (PageData pageData : l1) {
                if (pageData.getString("name").contains("国资")) {
                    org.putAll(pageData);
                    break;
                }
            }
            if(TokenUtil.getTokenOrgId().equals(org.getString("id"))){
                String nowStr = DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
                List<PageData> gzwUnits = new ArrayList<>();
                if (orgService.getDTFlag(nowStr)){
                    gzwUnits  = orgzationDao.findGZWUnitsFilterDT();
                }else {
                    gzwUnits = orgzationDao.findGZWUnits();
                }
                org.put("children", gzwUnits);
                l.add(org);
            }else{
               PageData p= orgzationDao.findbyid(TokenUtil.getTokenOrgId());
                l.add(p);
            }
            ListResult objResult = new ListResult(CommonCode.SUCCESS);
            objResult.setList(l);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    /**
     * 只获取当前pid下的子单位 不包含孙子级
     */
    public List<PageData> getChildrenByPId(String parentId) {
        try {
            PageData pd = new PageData();
            pd.put("parentId", parentId);
            List<PageData> list = orgzationDao.list(pd);
            return list;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    public ObjResult getGroupbyId(PageData pd) {
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        try {
            List<PageData> list = orgzationDao.list(null);
            String proId = pd.getString("proId");
            String orgId = pd.getString("orgId");
            if (StringUtil.isNotBlank(proId)){
                PropertyBasics basics = propertyBasicsMapper.selectById(proId);
                if (StringUtil.isNotBlank(basics.getOrgId())){
                    PageData groupbyId = getGroupbyId(basics.getOrgId(), list);
                    objResult.setPageData(groupbyId);
                }else {
                    //所属集团全称
                    String affiliatedOrgFullName = basics.getAffiliatedOrgFullName();
                    List<PageData> byName = orgzationDao.findByName(affiliatedOrgFullName);
                    if (CollectionUtil.isNotEmpty(byName)){
                        objResult.setPageData(byName.get(0));
                    }
                }
            }
            if (StringUtil.isNotBlank(orgId)){
                objResult.setPageData(getGroupbyId(orgId, list));
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }

        return objResult;
    }

    public R<PageData> getGroupTree(){
        try {
            String orgId = TokenUtil.getTokenOrgId();
            List<PageData> list = orgzationDao.list(null);
            PageData groupOrg = getGroupbyId(orgId, list);
            if(groupOrg == null){
                groupOrg = orgzationDao.findbyid(orgId);
            }
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> listTree = treeUtli.getNoEmptyChild(groupOrg.getString("id"), list);
            if (CollectionUtil.isNotEmpty(listTree)){
                groupOrg.put("children", listTree);
            }
            return R.data(groupOrg);
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
            return R.fail();
        }

    }

    /**
     * 根据orgId 获取企业级次 isUnit =1 算一级
     * @param orgId
     * @return
     */
    public Integer getGrade(String orgId){
        try {
            List<PageData> list = orgzationDao.list(null);
            return getGrade(orgId, list, 0);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    private Integer getGrade(String id, List<PageData> org, Integer grade){
        if (Tools.notEmpty(id)) {
            for (PageData pageData : org) {
                if (pageData.getString("id").equals(id)) {
                    if (Tools.notEmpty(pageData.getString("isunit")) &&
                            "1".equals(pageData.getString("isunit"))) {
                        grade++;
                        return grade;
                    } else {
                        if ("0".equals(pageData.getString("parentId")) || Tools.isEmpty(pageData.getString("parentId"))) {
                            break;
                        } else {
                            grade++;
                            return getGrade(pageData.getString("parentId"), org, grade);
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据单位id查询集团
     * 所有集团
     *
     * @return
     */
    public PageData  getGroupbyId(String id, List<PageData> org) {
        if (Tools.notEmpty(id)) {
            for (PageData pageData : org) {
                if (pageData.getString("id").equals(id)) {
                    if (Tools.notEmpty(pageData.getString("isunit")) &&
                            "1".equals(pageData.getString("isunit"))) {
                        return pageData;
                    } else {
                        if ("0".equals(pageData.getString("parentId")) || Tools.isEmpty(pageData.getString("parentId"))) {
                            break;
                        } else {
                            PageData p = getGroupbyId(pageData.getString("parentId"), org);
                            if (p != null) {
                                return p;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取下级及本级单位树,忽略虚拟节点
     *
     * @return
     */
    public ListResult getSubordinatePassFictitious() {
        ListResult listResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.listForGzw();
            TreeUtli treeUtli=new TreeUtli();
            getChlidPassFictitious(orgId, orgAll);
            List<PageData> list=orgAll.stream().filter(pageData -> !"3".equals(pageData.getString("type"))).collect(Collectors.toList());
            List<PageData> l = new ArrayList<>();
            p.put("children",treeUtli.getChlid(p.getString("id"),list));
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    public ListResult getPassFictitious() {
        ListResult listResult;
        try {
            String orgId = gzwProperties.getId();
            PageData p = orgzationDao.findbyid(orgId);
            List<PageData> orgAll = orgzationDao.listForGzw();
            TreeUtli treeUtli=new TreeUtli();
            getChlidPassFictitious(orgId, orgAll);
            List<PageData> list=orgAll.stream().filter(pageData -> !"3".equals(pageData.getString("type"))).collect(Collectors.toList());
            List<PageData> l = new ArrayList<>();
            p.put("children",treeUtli.getChlid(p.getString("id"),list));
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取 13 家集团企业
     * @return
     */
    public ListResult findThirteen() {
        ListResult listResult;
        try {
            List<PageData> p = orgzationDao.findThirteen();
            TreeUtli treeUtli=new TreeUtli();
            List<PageData> pageData = treeUtli.NoParentIdtree(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(pageData);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    /**
     * 获取 13 家集团企业
     * @return
     */
    public ListResult findThirteenOrg() {
        ListResult listResult;
        try {
            List<PageData> p = orgzationDao.findThirteen();
            TreeUtli treeUtli=new TreeUtli();
            List<PageData> pageData = treeUtli.NoParentIdtree(p);
            //添加国资委
            List<PageData> list = orgzationDao.findByName(gzwProperties.getName());
            if (CollectionUtil.isNotEmpty(list) && list.size() == 1){
                pageData.add(list.get(0));
            }
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(pageData);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }


    public boolean isParent(String orgId){
        boolean flag = false;
        try {
            List<PageData> orgAll = orgzationDao.list(null);

            if (CollectionUtil.isNotEmpty(orgAll)){
                for (PageData org : orgAll){
                    if (orgId.equals(org.getString("parentId"))){
                        flag = true;
                        break;
                    }
                }
            }
        }catch (Exception e){

        }
        return flag;
    }

    public ObjResult isHaveChild(){
        ObjResult objResult;
        try {
            String orgId = TokenUtil.getTokenOrgId();
            objResult = new ObjResult(CommonCode.SUCCESS);
            PageData pd = new PageData();
            pd.put("flag", isParent(orgId));
            objResult.setPageData(pd);
        }catch (Exception e){
            objResult = new ObjResult(CommonCode.FAIL);
        }
        return objResult;
    }

    public void getChlidPassFictitious(String pid, List<PageData> listAll) {
        //得到当前下的子节点
        for (PageData pageData : listAll) {
            if (pageData.getString("parentId").equals(pid)) {
                if ("3".equals(pageData.getString("type"))
                ) {
                    String id="";
                    for (PageData p : listAll) {
                        if(p.getString("id").equals(pid)){
                             id=p.getString("parentId");
                            break;
                        }
                    }
                    if(Tools.notEmpty(id)&&!"0".equals(id)){
                        pageData.put("parentId",id);
                    }
                    getChlidPassFictitious(pageData.getString("id"),listAll);
                }else{
                    PageData p1=new PageData();
                    for (PageData p : listAll) {
                        if(p.getString("id").equals(pid)){
                            p1=p;
                            break;
                        }
                    }
                    if(p1!=null){
                        if("3".equals(p1.getString("type"))){
                            pageData.put("parentId",p1.getString("parentId"));
                        }
                    }
                }
            }
        }
    }

    /**
     * 前台的新增子节点,保存，自动生成编码
     *
     * @param pd
     * @return
     */

    public ObjResult saveNoOrgcode(PageData pd) {
        ObjResult objResult;
        try {
            String name = pd.getString("name");
            if(StringUtils.isBlank(name)) return new ObjResult("请填写单位名称");
            PageData repeat = orgzationDao.findRepeatName(name.trim());
            if(null != repeat) return new ObjResult("单位名称重复");

            String id = pd.getString("parentId");
            PageData findbyid = orgzationDao.findbyid(id);
            String Orgcode = findbyid.getString("orgCode");
            //判断预算表类型
            Integer typeCode = findbyid.getInteger("typeCode");
            if(Optional.ofNullable(typeCode).isPresent()){
                if (typeCode == 1){
                    findbyid.put("typeCode","0");
                    //保存父节点
                    orgzationDao.edit(findbyid);
                    OrgCache.update(id);
                }
            }

            //判断orgCode
            PageData pd2 = new PageData();
            pd2.put("parentId", id);
            List<PageData> list = orgzationDao.list(pd2);
            int orgnum = 0;
            for (PageData pageData : list){
                //截取最后两位
                String orgCode = pageData.getString("orgCode");
                int tempnum = Integer.valueOf(orgCode.substring(orgCode.length()-2,orgCode.length()));
                if (tempnum>orgnum){
                    orgnum = tempnum;
                }
            }
            orgnum = orgnum+1;
            if (orgnum < 10){
                Orgcode = Orgcode+"0"+orgnum;
            }else {
                Orgcode = Orgcode+orgnum;
            }
            if (pd.getString("orgCode") != null){
                Orgcode = pd.getString("orgCode")+Orgcode;
            }
            pd.put("orgCode", Orgcode);
            if (Tools.isEmpty(pd.getString("parentId"))) {
                pd.put("parentId", "0");
            }
            pd.put("id", UuidUtil.get32UUID());
            if (Optional.ofNullable(typeCode).isPresent()){
                pd.put("typeCode", 1);
            }
            Integer forgzw = findbyid.getInteger("FORGZW");
            pd.put("FORGZW", forgzw);
            pd.put("createTime", DateUtil.now());
            orgzationDao.save2(pd);
            OrgCache.update(pd.getString("id"));

            List<PageData> list_pro = propertyBasicsDao.list(null);List<PageData> list1 = new ArrayList<>();
            for (PageData pro : list_pro) {
                if (pd.getString("name").equals(pro.getString("orgName"))) {
                    PageData pd3 = new PageData();
                    pd3.put("id", pro.getString("id"));
                    pd3.put("orgId", pd.getString("id"));
                    propertyBasicsDao.editByOrgId(pd3);
                    propertyDao.editByOrgId(pd3);
                    break;
                }
            }
            objResult = new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            objResult = new ObjResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return objResult;
    }

    /**
     * 获取除了自己和自己的子集的树
     * @param pd
     * @return
     */
    public ListResult<PageData> getSubordinatePassOwns(PageData pd){
        ListResult listResult;
        try {
            //获取自己和子集
            String id = pd.getString("id");
            String orgId = TokenUtil.getTokenOrgId();
            PageData p = orgzationDao.findbyid(orgId);
            PageData p2 = orgzationDao.findbyid(id);
            List<PageData> orgAll = orgzationDao.list(null);
            orgAll.remove(p2);
            TreeUtli treeUtli = new TreeUtli();
            List<PageData> list_tree = treeUtli.getChlid(orgId, orgAll,id);
            p.put("children", list_tree);
            List<PageData> l = new ArrayList<>();
            l.add(p);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(l);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;
    }

    public ListResult<String> getFillingOrg(Integer formType){

        ListResult<String> listResult;
        FormTableEnum formTableEnum = FormTableEnum.getByFormType(formType);
        if (formTableEnum == null){
            listResult = new ListResult(CommonCode.SUCCESS);
            return listResult;
        }

        String sql = "select distinct " + formTableEnum.getOrgColumnName() + " from " + formTableEnum.getTableName();
        String whereSql = " where 1 = 1 ";
        if (formTableEnum.isHaveStatus()){
            whereSql += " and status = 3 ";
        }

        if(formTableEnum.isHaveDeleted()){
            whereSql += " and is_deleted = 0 ";
        }

        sql += whereSql;



        try {
            List<String> fillingOrgs = orgzationDao.getFillingOrg(sql);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(fillingOrgs);
        } catch (Exception e) {
            listResult = new ListResult(CommonCode.FAIL);
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return listResult;

    }

    public ObjResult createProperty(String orgId) {
        try {
            PageData pageData = propertyBasicsDao.findByorgId(orgId);
            if (CollectionUtil.isNotEmpty(pageData)) {
                if(StringUtils.isNotBlank(pageData.getString("orgId"))
                        && StringUtils.isBlank(pageData.getString("orgGradation"))){
                    Integer orgLevel = this.getOrgLevel(orgId);
                    if(orgLevel == 0){
                        pageData.put("orgGradation","001099");
                    }else if(orgLevel == 1){
                        pageData.put("orgGradation","001001");
                    }else if(orgLevel == 2){
                        pageData.put("orgGradation","001002");
                    }else if(orgLevel == 3){
                        pageData.put("orgGradation","001003");
                    }else if(orgLevel == 4){
                        pageData.put("orgGradation","001004");
                    }else if(orgLevel == 5){
                        pageData.put("orgGradation","001005");
                    }else if(orgLevel == 6){
                        pageData.put("orgGradation","001006");
                    }else if(orgLevel == 7){
                        pageData.put("orgGradation","001007");
                    }
                    propertyDao.edit(pageData);
                    propertyBasicsDao.edit(pageData);
                }
//                return new ObjResult(CustomCode.builder().message("该单位产权数据已绑定！").code(1999).success(false).build());
                return new ObjResult(CommonCode.SUCCESS);
            }

            PageData org = orgzationDao.findbyid(orgId);
            if (CollectionUtil.isEmpty(org)) {
                return new ObjResult(CustomCode.builder().message("该单位数据不存在！").code(1999).success(false).build());
            }

            String parentOrgId = org.getString("parentId");
            PageData property = new PageData();
            property.put("id", UuidUtil.get32UUID());
            property.put("orgId", orgId);
            property.put("status", FormStatusConstant.FINISH);
            property.put("formType", FormTypeConstant.PM_PROPERTY_FORM);
            property.put("createTime", DateUtil.now());
            property.put("updateTime", DateUtil.now());
            property.put("orgName", org.getString("orgName"));
            property.put("initialId", property.getString("id"));
            property.put("competentOrganization", getCompetentOrganization(orgId));
            if (!"0".equals(parentOrgId)){
                 PageData parentProperty = propertyBasicsDao.findByorgId(parentOrgId);
                if (CollectionUtil.isEmpty(parentProperty)) {
                    return new ObjResult(CustomCode.builder().message("该单位父节点 产权数据不存在！").code(1999).success(false).build());
                }
                property.put("parentId", parentProperty.getString("id"));
            }
            // 设置企业级次
            Integer orgLevel = this.getOrgLevel(orgId);
            if(orgLevel == 0){
                property.put("orgGradation","001099");
            }else if(orgLevel == 1){
                property.put("orgGradation","001001");
            }else if(orgLevel == 2){
                property.put("orgGradation","001002");
            }else if(orgLevel == 3){
                property.put("orgGradation","001003");
            }else if(orgLevel == 4){
                property.put("orgGradation","001004");
            }else if(orgLevel == 5){
                property.put("orgGradation","001005");
            }else if(orgLevel == 6){
                property.put("orgGradation","001006");
            }else if(orgLevel == 7){
                property.put("orgGradation","001007");
            }
            propertyDao.save(property);
            propertyBasicsDao.save(property);
            propertyRecordDao.save(property);
            if(parentOrgId==null||parentOrgId.equals("")){
                propertyBasicsService.changeNewPropertyCodeGzw(property.getString("id"));//如果是国资委就赋初始化的产权级别和产权code初始化值
            }

            if (!"0".equals(parentOrgId)) {
                propertyBasicsService.changeNewPropertyCode(property.getString("id"), property.getString("parentId"));
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);

        }
        return new ObjResult(CommonCode.SUCCESS);
    }

    public ObjResult deleteProperty(String orgId) {
        try {
            PageData pageData = propertyBasicsDao.findByorgId(orgId);
            if (CollectionUtil.isEmpty(pageData)) {
                return new ObjResult(CustomCode.builder().message("该单位无产权数据！").code(1999).success(false).build());
            }
            PageData queryPageData = new PageData();
            String propertyId = pageData.getString("id");
            queryPageData.put("parentId", propertyId);
            if (CollectionUtil.isNotEmpty(propertyBasicsDao.findChild(queryPageData))){
                return new ObjResult(CustomCode.builder().message("该单位子节点 有产权数据，无法删除！").code(1999).success(false).build());
            }
            List<String> ids = new ArrayList<>();

            ids.add(propertyId);
            propertyDao.del_ids(ids);
            propertyBasicsDao.delByIds(ids);
            propertyRecordDao.delByIds(ids);

        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);

        }
        return new ObjResult(CommonCode.SUCCESS);
    }


    /**
     * 判断是否为集团
     * @param orgId
     * @return
     */
    public boolean isUnit(String orgId){
        boolean result = false;
        try {
            PageData p = orgzationDao.findbyid(orgId);
            if ("1".equals(p.getString("isunit"))){
                result = true;
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return result;
    }

//    public boolean isGzw(String orgId){
//        boolean result = false;
//        try {
//            PageData p = orgzationDao.findbyid(orgId);
//            if ("1".equals(p.getString("type"))){
//                result = true;
//            }
//
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return result;
//    }

    /**
     * 根据组织id获取所属集团
     * @param orgId
     * @return
     */
    public String getUnitId(String orgId){
        String unitId = "";
        try {
            List<PageData> all = orgzationDao.list(null);
            List<String> ids = all.stream().filter(p -> "1".equals(p.getString("isunit")))
                    .map(p -> p.getString("id"))
                    .collect(Collectors.toList());
            PageData org = orgzationDao.findbyid(orgId);
            unitId = findIdByIds(org, all, ids);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return unitId;
    }

    /**
     * 根据组织id获取所属集团
     * @param org
     * @param all
     * @return
     */
    public String getUnitId(PageData org, List<PageData> all){
        String unitId = "";
        try {
            List<String> ids = all.stream().filter(p -> "1".equals(p.getString("isunit")))
                    .map(p -> p.getString("id"))
                    .collect(Collectors.toList());
            unitId = findIdByIds(org, all, ids);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return unitId;
    }

    /**
     * 根据组织id获取所属集团
     * @param org
     * @param all
     * @return
     */
    public PageData getOrgUnit(PageData org, List<PageData> all){
        if(null == org) return null;
        PageData unit = null;
        try {
            List<String> ids = all.stream().filter(p -> "1".equals(p.getString("isunit")))
                    .map(p -> p.getString("id"))
                    .collect(Collectors.toList());
            unit = findUnitByOrg(org, all, ids);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return unit;
    }

    /**
     * 根据组织id获取所属国资委
     * @param orgId
     * @return
     */
    public String getCompetentOrganization(String orgId){
        String competentOrganization = "";
        try {
            List<PageData> all = orgzationDao.list(null);
//            List<String> ids = all.stream().filter(p -> "1".equals(p.getString("type")))
//                    .map(p -> p.getString("id"))
//                    .collect(Collectors.toList());
            List<String> ids = all.stream().filter(p -> "4".equals(p.getString("type")))//2024-12-21 根据目前的系统来看国资委的type应该为4 暂时这样改不对的话再改回来
                    .map(p -> p.getString("id"))
                    .collect(Collectors.toList());
            PageData org = orgzationDao.findbyid(orgId);
            competentOrganization = findIdByIds(org, all, ids);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return competentOrganization;
    }

    /**
     * 根据组织id获取所属国资委
     * @param org
     * @param all
     * @param orgId
     * @return
     */
    public String getCompetentOrganization(PageData org, List<PageData> all, String orgId){
        String competentOrganization = "";
        try {
//            List<String> ids = all.stream().filter(p -> "1".equals(p.getString("type")))
//                    .map(p -> p.getString("id"))
//                    .collect(Collectors.toList());
            List<String> ids = all.stream().filter(p -> "4".equals(p.getString("type")))//2024-12-21 根据目前的系统来看国资委的type应该为4 暂时这样改不对的话再改回来
                    .map(p -> p.getString("id"))
                    .collect(Collectors.toList());
            competentOrganization = findIdByIds(org, all, ids);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return competentOrganization;
    }

    public PageData findByName(String orgName, String competentOrganization){
        try {
            List<PageData> list = orgzationDao.findByName(orgName.trim());
            if (CollectionUtil.isNotEmpty(list) && list.size() == 1){
                return list.get(0);
            }

            for (PageData org : list){
                if (competentOrganization.equals(getCompetentOrganization(org.getString("id")))){
                    return org;
                }
            }

        } catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
       return null;
    }

    /**
     * 获取国资委id
     * @return
     */
    public String getGzwId(){
        try {
            List<PageData> list = orgzationDao.findByName(gzwProperties.getName());
            if (CollectionUtil.isNotEmpty(list) && list.size() == 1){
                return list.get(0).getString("id");
            }
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        return null;
    }

    /**
     * 判断当前节点名称和国资委是否相等
     * @param orgId
     * @return
     */
    public boolean checkGzwName(String orgId){
        String orgName = getNameById(orgId);
        return gzwProperties.getName().equals(orgName);
    }

    /**
     * 寻找父节点id在ids集合中的节点
     * @param org
     * @param all
     * @param ids
     * @return
     */
    private String findIdByIds(PageData org, List<PageData> all, List<String> ids){
        if (ids.contains(org.getString("id"))){
            return org.getString("id");
        }

        for (PageData p : all){
            if (p.getString("id").equals(org.getString("parentId"))){
                if (ids.contains(p.getString("id"))){
                    return p.getString("id");
                }else {
                    return findIdByIds(p, all, ids);
                }
            }
        }

        return null;
    }

    /**
     * 寻找指定组织的所属集团
     * @param org
     * @param all
     * @param ids
     * @return
     */
    private PageData findUnitByOrg(PageData org, List<PageData> all, List<String> ids){
        if (ids.contains(org.getString("id"))){
            return org;
        }

        for (PageData p : all){
            if (p.getString("id").equals(org.getString("parentId"))){
                if (ids.contains(p.getString("id"))){
                    return p;
                }else {
                    return findUnitByOrg(p, all, ids);
                }
            }
        }

        return null;
    }

    /**
     * 根据指定ID获取该节点及其所有子节点的ID集合
     * @param rootList 树形结构的根节点列表
     * @param targetId 要查找的目标ID
     * @return 包含目标节点及其所有子节点ID的集合
     */
    public List<String> getSubtreeIds(List<PageData> rootList, String targetId) {
        List<String> result = new ArrayList<>();
        for (PageData root : rootList) {
            PageData targetNode = findNodeById(root, targetId);
            if (targetNode != null) {
                collectSubtreeIds(targetNode, result);
                break;
            }
        }
        return result;
    }

    /**
     * 递归查找指定ID的节点
     */
    private static PageData findNodeById(PageData node, String targetId) {
        if (node.getString("id").equals(targetId)) {
            return node;
        }

        List<PageData> children = (List<PageData>) node.get("children");
        if (children != null) {
            for (PageData child : children) {
                PageData found = findNodeById(child, targetId);
                if (found != null) {
                    return found;
                }
            }
        }
        return null;
    }

    /**
     * 递归收集子树所有ID
     */
    private static void collectSubtreeIds(PageData node, List<String> idList) {
        idList.add(node.getString("id"));
        List<PageData> children = (List<PageData>) node.get("children");
        if (children != null) {
            for (PageData child : children) {
                collectSubtreeIds(child, idList);
            }
        }
    }

    /**
     * 获取指定orgId的企业层级
     * @param orgId
     * @return
     * @throws Exception
     */
    public Integer getOrgLevel(String orgId) throws Exception {
        PageData pd = new PageData();
        List<PageData> orgAll = orgzationDao.list(pd);
        TreeUtli treeUtli = new TreeUtli();
        List<PageData> list_tree = treeUtli.NoParentIdtree(orgAll);
        for (PageData org : list_tree) {
            int level = findLevel(orgId, org, 0);
            if (level != -1) {
                return level;
            }
        }
        return -1;
    }

    private static int findLevel(String targetId, PageData currentOrg, int currentLevel) {
        if (targetId.equals(currentOrg.getString("orgId"))) {
            return currentLevel;
        }
        List<PageData> children = (List<PageData>) currentOrg.get("children");
        if (children != null) {
            for (PageData child : children) {
                int level = findLevel(targetId, child, currentLevel + 1);
                if (level != -1) {
                    return level;
                }
            }
        }
        return -1;
    }


    /**
     * 检查myId是否从属于targetId
     * @param myId
     * @param targetId
     * @param treeList
     * @return
     */
    public boolean isInSubtree(String myId, String targetId, List<PageData> treeList) {
        // 先找到目标节点
        PageData targetNode = findNodeById(targetId, treeList);;
        if (targetNode == null) {
            return false; // 目标节点不存在
        }
        // 检查myId是否在目标节点的子树中
        return checkSubtree(myId, targetNode);
    }


    private static PageData findNodeById(String id, List<PageData> nodes) {
        if (nodes == null) return null;

        for (PageData node : nodes) {
            if (node.getString("id").equals(id)) {
                return node;
            }
            PageData found = findNodeById(id, (List<PageData>) node.get("children"));
            if (found != null) {
                return found;
            }
        }
        return null;
    }

    private static boolean checkSubtree(String myId, PageData node) {
        if (node == null) return false;
        if (node.getString("id").equals(myId)) return true;
        List<PageData> childList = (List<PageData>) node.get("children");
        if (childList != null) {
            for (PageData child : childList) {
                if (checkSubtree(myId, child)) {
                    return true;
                }
            }
        }
        return false;
    }
}
